/**
 * 全局WebSocket连接管理器
 * 防止同一用户创建多个相同类型的连接
 */
class GlobalWebSocketManager {
  constructor() {
    this.connections = new Map() // 存储不同类型的连接
    this.connectionStates = new Map() // 存储连接状态
  }

  /**
   * 获取连接的唯一标识
   */
  getConnectionKey(type, roomId = '', gameType = '') {
    if (type === 'roomList') {
      return 'roomList'
    } else if (type === 'gameRoom') {
      return `gameRoom_${gameType}_${roomId}`
    } else if (type === 'chatRoom') {
      return `chatRoom_${roomId}`
    }
    return `${type}_${roomId}`
  }

  /**
   * 检查是否已有相同类型的连接
   */
  hasConnection(type, roomId = '', gameType = '') {
    const key = this.getConnectionKey(type, roomId, gameType)
    return this.connections.has(key)
  }

  /**
   * 获取现有连接
   */
  getConnection(type, roomId = '', gameType = '') {
    const key = this.getConnectionKey(type, roomId, gameType)
    return this.connections.get(key)
  }

  /**
   * 注册连接
   */
  registerConnection(type, roomId = '', gameType = '', manager) {
    const key = this.getConnectionKey(type, roomId, gameType)
    this.connections.set(key, manager)
    this.connectionStates.set(key, {
      isConnected: false,
      isConnecting: false,
      lastActivity: Date.now()
    })
    console.log(`注册WebSocket连接: ${key}`)
  }

  /**
   * 注销连接
   */
  unregisterConnection(type, roomId = '', gameType = '') {
    const key = this.getConnectionKey(type, roomId, gameType)
    this.connections.delete(key)
    this.connectionStates.delete(key)
    console.log(`注销WebSocket连接: ${key}`)
  }

  /**
   * 更新连接状态
   */
  updateConnectionState(type, roomId = '', gameType = '', state) {
    const key = this.getConnectionKey(type, roomId, gameType)
    const currentState = this.connectionStates.get(key)
    if (currentState) {
      Object.assign(currentState, state)
      currentState.lastActivity = Date.now()
    }
  }

  /**
   * 关闭所有连接
   */
  closeAllConnections() {
    console.log('关闭所有WebSocket连接')
    for (const [key, manager] of this.connections) {
      try {
        if (manager && typeof manager.close === 'function') {
          manager.close()
        }
      } catch (error) {
        console.error(`关闭连接失败: ${key}`, error)
      }
    }
    this.connections.clear()
    this.connectionStates.clear()
  }

  /**
   * 获取连接统计信息
   */
  getConnectionStats() {
    const stats = {
      totalConnections: this.connections.size,
      connections: []
    }
    
    for (const [key, manager] of this.connections) {
      const state = this.connectionStates.get(key)
      stats.connections.push({
        key,
        isConnected: manager?.getConnected() || false,
        isConnecting: manager?.getConnecting() || false,
        lastActivity: state?.lastActivity || 0
      })
    }
    
    return stats
  }
}

// 创建全局WebSocket管理器实例
const globalWSManager = new GlobalWebSocketManager()

export default globalWSManager 